package com.nantes.nantourage.utils;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import org.apache.http.client.utils.URIUtils;

import android.util.Log;

/**
 * Cette classe fournit des m�thodes permettant de formater les adresses web et d'extraire les donn�es de ces adresses
 * 
 * @author bourys
 */
public class WebServiceHelper {

    private static final String ENCODING_FORMAT = "UTF-8";

    public static URI generateServiceURL(String scheme, String host, int port, String serviceBase) {
        try {
            return URIUtils.createURI(scheme, host, port, serviceBase, null, null);
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String formatParametres(Map<String, String> params) {

        String url = "";
        int i = 0;
        for(Map.Entry<String, String> param : params.entrySet()) {

            if(i == 0) {
                url += "?";
            } else {
                url += "&";
            }

            try {
                url += param.getKey() + "=" + URLEncoder.encode(param.getValue(), ENCODING_FORMAT);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            i++;
        }

        return url;
    }

    public static int getPort(String url) {
        URL util;
        try {
            util = new URL(url);
            return util.getPort() != -1 ? util.getPort() : util.getDefaultPort();
        } catch (MalformedURLException e) {
            Log.e("URL mal formée : " + url, e.toString());
        }
        return 443;
    }

    public static String getProtocol(String url) {
        URL util;
        try {
            util = new URL(url);
            return util.getProtocol();
        } catch (MalformedURLException e) {
            Log.e("URL mal formée : " + url, e.toString());
        }
        return "";
    }
}
